package com.zx.tradeclient.ctrl.index5;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.base.ctrl.BaseActivity;
import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.util.AESEncryptor;
import com.zx.base.util.ActivityTaskManager;
import com.zx.base.widget.QuitDialog;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.ctrl.index6.CustomerCenterActivity;

public class LoginActivity extends BaseActivity {
	/** Called when the activity is first created. */
	private TradeApp app;
	private CheckBox isRemember;
	private EditText username, password;
	private TextView jump, login_text_forget;
	private Button enter;
	private SharedPreferences sp;
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (TradeApp) getApplication();
		if (!(ActivityTaskManager.getInstance().containsName("LoginActivity"))) {
			ActivityTaskManager.getInstance()
					.putActivity("LoginActivity", this);
		}
		setContentView(R.layout.login);
		init();

	}

	private void init() {
		setHeader(5);
		isRemember = (CheckBox) findViewById(R.id.login_check_remember);
		username = (EditText) findViewById(R.id.login_edit_username);
		password = (EditText) findViewById(R.id.login_edit_password);
		enter = (Button) findViewById(R.id.login_button_main);
		jump = (TextView) findViewById(R.id.login_text_jump);
		login_text_forget = (TextView) findViewById(R.id.login_text_forget);

		login_text_forget.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 忘记密码
				progressDialog = ProgressDialog.show(LoginActivity.this, null,
						"正在获取信息，请稍后.....", true, true);
				getCompanyInfo();

			}
		});

		sp = getSharedPreferences(Constant.PREFERENCE_NAME,
				Activity.MODE_PRIVATE);
		username.setText(sp.getString(Constant.USERNAME, null));
		isRemember.setChecked(sp.getBoolean(Constant.REMENBER_PASSWORD, false));
		if (isRemember.isChecked()) {
			String pwd = "";
			try {
				pwd = AESEncryptor.decrypt(Constant.KEY,
						sp.getString(Constant.PASSWORD, ""));
			} catch (Exception e) {
				e.printStackTrace();

			}
			password.setText(pwd);
		}

		enter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				progressDialog = ProgressDialog.show(LoginActivity.this, null,
						"正在提交数据数据，请稍后.....", true, true);
				userTask();
			}
		});
		jump.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 跳到注册
				Intent intent = new Intent(LoginActivity.this,
						RegisterActivity.class);
				startActivity(intent);
				//LoginActivity.this.finish();
			}
		});
		sp = getSharedPreferences(Constant.PREFERENCE_NAME,
				Activity.MODE_PRIVATE);
	}

	// 异步操作
	private void userTask() {

		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "login");
		map.put("username", username.getText().toString().trim());
		map.put("password", password.getText().toString().trim());
		map.put("imei", app.getImei());
		map.put("imsi", app.getImsi());
		map.put("version", app.getVersion());
		map.put("phone", app.getPhone());
		map.put("phonetype", app.getPhoneType());
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(LoginActivity.this, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}
		});
	}

	// 解析获取的服务器json数据
	private void parseJson(JSONObject response) {
		try {
			String succeed = response.getString("succeed");
			if (succeed.equals("000")) {
				String data = response.getString("userData");

				String u_id = new JSONObject(data).getString("id");
				app.user.setId(u_id);
				String loginName = new JSONObject(data).getString("loginName");
				app.user.setLoginName(loginName);
				String creditRating = new JSONObject(data)
						.getString("creditRating");
				app.user.setCreditRating(creditRating);
				String icon = new JSONObject(data).getString("icon");
				app.user.setIcon(icon);
				String company = new JSONObject(data).getString("company");
				app.user.setCompany(company);
				// 记住用户名

				SharedPreferences.Editor editor = sp.edit();
				String userName = username.getText().toString().trim();
				String passWord = password.getText().toString().trim();
				editor.putString(Constant.USERNAME, userName);
				try {
					passWord = AESEncryptor.encrypt(Constant.KEY, passWord);
					editor.putString(Constant.PASSWORD, passWord);
				} catch (Exception e) {
					e.printStackTrace();
				}
				editor.putBoolean(Constant.REMENBER_PASSWORD,
						isRemember.isChecked());
				editor.commit();
				try {
					if(getIntent().getStringExtra("status")==null){
						goback();
					}else{
						Intent intent=new Intent(LoginActivity.this,UserCenterActivity.class);
						startActivity(intent);
					}
				} catch (Exception e) {
					Intent intent=new Intent(LoginActivity.this,UserCenterActivity.class);
					startActivity(intent);
				}
				
					
				
				
				//LoginActivity.this.finish();

			} else if (succeed.equals("001")) {
				Toast toast = Toast.makeText(LoginActivity.this, "用户名不存在",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} else if (succeed.equals("002")) {
				Toast toast = Toast.makeText(LoginActivity.this, "密码不正确",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} else if (succeed.equals("003")) {
				Toast toast = Toast.makeText(LoginActivity.this, "用户名密码为空",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			if (progressDialog != null)
				progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (Constant.debug)
				Log.d("TMG", "ManageActivity KEYCODE_BACK");
			QuitDialog dialog = new QuitDialog(LoginActivity.this);
			dialog.exitConfirm();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void getCompanyInfo() {

		Map<String, String> map = new HashMap<String, String>(); // 登录时向服务器发送的参数
		map.put("act", "aboutUs");

		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJsonCenter(response);

			}

			@Override
			public void onFailure(Throwable e) {
				progressDialog.dismiss();
				Toast toast2 = Toast.makeText(LoginActivity.this, "错误",
						Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();

			}
		});
	}

	private void parseJsonCenter(JSONObject response) {

		try {
			JSONObject object = response;
			String succeed = object.getString("succeed");

			if (succeed.equals("000")) {

				Intent intent = new Intent(LoginActivity.this,
						CustomerCenterActivity.class);
				intent.putExtra("phone", object.getString("phoneNumber"));
				startActivity(intent);

			} else {
				Toast toast2 = Toast.makeText(LoginActivity.this, "无数据",
						Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
			}

			progressDialog.dismiss();

		} catch (JSONException e) {
			progressDialog.dismiss();
			e.printStackTrace();
		}
	}

}